from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.response import Response
from apps.minapp import models
from apps.minapp.models import Window, Photo_Window
from rest_framework import serializers
from rest_framework.views import APIView
import datetime
import django.utils.timezone as timezone
import traceback


class WindowSerializer(serializers.ModelSerializer):
    icon = serializers.CharField()
    photos = serializers.SerializerMethodField()

    class Meta:
        model = Window
        fields = "__all__"
        depth = 1

    def get_photos(self, obj):
        photoList = []
        for photo in obj.photos.all():
            photoList.append(photo.src)
        return photoList


class PhotosSerializers(serializers.ModelSerializer):
    photos = serializers.SerializerMethodField()

    class Meta:
        model = Window
        fields = ['photos']
        # fields = "__all__"
        depth = 1

    def get_photos(self, obj):
        photoList = []
        for photo in obj.photos.all():
            photoList.append(photo.src)
        return photoList


class WindowView(UpdateModelMixin, RetrieveModelMixin, GenericViewSet):
    queryset = models.Window.objects.all()
    serializer_class = WindowSerializer

    def retrieve(self, request, *args, **kwargs):
        shop_id = self.request.user.shop_id
        print(self.request.user)
        shop = self.get_queryset().get(id=shop_id)
        return Response(WindowSerializer(shop).data)

    def update(self, request, *args, **kwargs):
        shop_id = self.request.user.shop_id
        shop_data = request.data
        photos = list(shop_data['photos'])
        print(photos)
        del shop_data['photos']
        try:
            shop = Window.objects.get(id=shop_id)
            orginPhotos = list((PhotosSerializers(instance=shop).data)['photos'])
            delPhotos = list(set(orginPhotos) - set(photos))
            print(delPhotos)
            if len(delPhotos) != 0:
                for photo in delPhotos:
                    delPhoto = Photo_Window.objects.get(src=photo)
                    delPhoto.delete()
            addPhotos = list(set(photos) - set(orginPhotos))
            print(addPhotos)
            if len(addPhotos) != 0:
                for photo in addPhotos:
                    Photo_Window.objects.create(owner=shop, src=photo)
            shop.__dict__.update(**shop_data)
            shop.save()
        except Exception as e:
            print(e)
            return Response({'err_num': -1})
        return Response({'err_num': 0})


class WindowIndexView(APIView):
    def get(self, requset, *args, **kwargs):
        id = kwargs['pk']
        window = models.Window.objects.all().get(id=id)
        return Response(WindowSerializer(window).data)


class WindowGoodsSerializer(serializers.ModelSerializer):
    src = serializers.CharField()

    class Meta:
        model = models.Cover
        fields = "__all__"


class DetailPhotoSerializers(serializers.ModelSerializer):
    photos = serializers.SerializerMethodField()

    class Meta:
        model = models.Detail
        fields = ['photos']
        depth = 1

    def get_photos(self, obj):
        photoList = []
        for photo in obj.detailsrc.all():
            photoList.append(photo.src)
        return photoList


class WindowGoodsView(CreateModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet):
    def get_serializer_class(self):
        if self.action == 'list':
            return WindowGoodsSerializer

    def get_queryset(self):
        shop_id = self.request.user.shop_id
        queryset = models.Cover.objects.filter(detail__shop__id=shop_id)
        return queryset

    def update(self, request, *args, **kwargs):
        print(request.data)
        id = kwargs['pk']
        data = request.data
        coverdata = data['cover']
        photos = data['photos']
        del data['cover'], data['photos']
        try:
            cover = models.Cover.objects.get(id=id)
            detail = cover.detail
            originPhotos = list((DetailPhotoSerializers(instance=detail).data)['photos'])
            delPhotos = list(set(originPhotos) - set(photos))
            if len(delPhotos) != 0:
                for photo in delPhotos:
                    delPhoto = models.DetailSrc.objects.get(src=photo)
                    delPhoto.delete()
            addPhotos = list(set(photos) - set(originPhotos))
            if len(addPhotos) != 0:
                for photo in addPhotos:
                    models.DetailSrc.objects.create(detail=detail, src=photo)
            detail.__dict__.update(**data)
            detail.save()
            cover.__dict__.update(**coverdata)
            cover.save()
            return Response({"err_num": 0})
        except Exception as e:
            print(e)
            return Response({"err_num": -1})

    def create(self, request, *args, **kwargs):
        staff = self.request.user
        shop_id = staff.shop_id
        shop = models.Window.objects.get(id=shop_id)
        data = request.data
        print(data)
        photots = data['photos']
        cover = data['cover']
        del data['cover']
        del data['photos']
        try:
            newcover = models.Cover.objects.create(**cover)
            newdetail = models.Detail.objects.create(cover=newcover, shop=shop, **data)
            for photo in photots:
                models.DetailSrc.objects.create(detail=newdetail, src=photo)
            return Response({"err_num": 0})
        except Exception as e:
            print(e)
            return Response({"err_num": -1})


class GoodsStatusView(APIView):
    def post(self, request, *args, **kwargs):
        print(request.data)
        id = kwargs['pk']
        cover = models.Cover.objects.get(id=id)
        mode = request.data['mode']
        if mode == '1':
            cover.disabled = 1
        elif mode == '2':
            cover.disabled = 0
        elif mode == '3':
            cover.recommended = 1
        elif mode == '4':
            cover.recommended = 0
        cover.save()
        return Response({'err_num': 0, 'recommended': cover.recommended, 'disabled': cover.disabled})


class WindowNoticeSerializer(serializers.ModelSerializer):
    publishTime = serializers.SerializerMethodField()
    status = serializers.SerializerMethodField()

    @staticmethod
    def get_publishTime(obj):
        return str(obj.publishTime)[:19]

    @staticmethod
    def get_status(obj):
        return obj.get_status_display()

    class Meta:
        model = models.S_Notice
        fields = ['publishTime', 'id', 'title', 'status']


class WindowNoticeDetailSerializer(serializers.ModelSerializer):
    publishTime = serializers.SerializerMethodField()
    status = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()

    @staticmethod
    def get_publishTime(obj):
        return str(obj.publishTime)[:19]

    @staticmethod
    def get_status(obj):
        return obj.get_status_display()

    @staticmethod
    def get_image(obj):
        images = obj.image.all().values_list('src', flat=True)
        # print(images)
        return images

    class Meta:
        model = models.S_Notice
        fields = "__all__"


class NoticeImageSerializer(serializers.ModelSerializer):
    photos = serializers.SerializerMethodField()

    def get_photos(self, obj):
        photolist = []
        for photo in obj.image.all():
            photolist.append(photo.src)
        return photolist

    class Meta:
        model = models.S_Notice
        fields = ['photos']


class NoticeManageView(ListModelMixin, UpdateModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin,
                       GenericViewSet):
    serializer_class = WindowNoticeSerializer

    def get_queryset(self):
        shop_id = self.request.user.shop_id
        queryset = models.S_Notice.objects.filter(window__id=shop_id, status__in=[2, 4]).order_by('-publishTime')
        return queryset

    def destroy(self, request, *args, **kwargs):
        notice_id = kwargs['pk']
        try:
            instance = models.S_Notice.objects.get(id=notice_id)
            instance.status = 3
            instance.save()
            return Response({'err_num': 0})
        except Exception as e:
            print(e)
            return Response({'err_num': -1})

    def create(self, request, *args, **kwargs):
        staff = self.request.user
        shop_id = staff.shop_id
        print('sds', shop_id)
        shop = models.Window.objects.get(id=shop_id)
        data = request.data
        print(data)
        photos = data['photos']
        try:
            newnotice = models.S_Notice.objects.create(
                window_id=shop_id,
                staff_id=staff.id,
                title=data['title'],
                content=data['content'],
                status=int(data['status']))
            if data['status'] == '2':
                newnotice.publishTime = timezone.now()
                newnotice.save()
            for photo in photos:
                models.NoticeImages.objects.create(notice=newnotice, src=photo)
            return Response({'err_num': 0})
        except Exception as e:
            print(e)
            return Response({'err_num': -1})

    def retrieve(self, request, *args, **kwargs):
        shop_id = self.request.user.shop_id
        notice_id = kwargs['pk']
        try:
            notice = models.S_Notice.objects.get(id=notice_id)
            return Response({'err_num': 0, 'msg': WindowNoticeDetailSerializer(notice).data})
        except Exception as e:
            print(e)
            return Response({'err_num': -1})

    def update(self, request, *args, **kwargs):
        notice_id = kwargs['pk']
        notice_data = request.data
        print(notice_data)
        photos = list(notice_data['photos'])
        print(photos)
        del notice_data['photos']
        try:
            notice = models.S_Notice.objects.get(id=notice_id)
            originPhotos = list(NoticeImageSerializer(instance=notice).data['photos'])
            delPhotos = list(set(originPhotos) - set(photos))
            print(delPhotos)
            if len(delPhotos) != 0:
                for photo in delPhotos:
                    delPhoto = models.NoticeImages.objects.get(src=photo)
                    delPhoto.delete()
            addPhotos = list(set(photos) - set(originPhotos))
            print(addPhotos)
            if len(addPhotos) != 0:
                for photo in addPhotos:
                    models.NoticeImages.objects.create(notice=notice, src=photo)
            notice.__dict__.update(**notice_data)
            notice.save()
            return Response({'err_num': 0})
        except Exception as e:
            print(e)
            print('traceback.print_exc(): ', traceback.print_exc())
            return Response({'err_num': -1})
